package com.leyou.auth.Servcie.impl;

import com.leyou.api.controller.FeignController;
import com.leyou.auth.Servcie.UserService;
import com.leyou.common.constants.JwtConstants;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.pojo.dto.Payload;
import com.leyou.pojo.dto.UserDetail;
import com.leyou.pojo.dto.UserDto;
import com.leyou.pojo.util.JwtUtils;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.common.constants.JwtConstants.COOKIE_NAME;
import static com.leyou.common.constants.JwtConstants.DOMAIN;
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private FeignController feignController;

    private UserDto userDto;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 用户登录校验
     * @param username
     * @param psssword
     */
    @Override
    public void login(String username, String psssword, HttpServletResponse response) {
        //查询用户
        try {
            userDto = feignController.queryUserByNameAndPsw(username, psssword);
        } catch (FeignException e) {
            throw new LyException(e.getMessage(),e.status());
        }
        //判断查询结果
        if(userDto==null){
            throw new LyException("用户名或密码错误", 400);
        }
        //生成jwt

        String jwt = jwtUtils.createJwt(UserDetail.of(userDto.getId().toString(),userDto.getUsername()));

        //写入redis,既然创建完jwt后就要写入redis，干脆将写入redis的操作放在jwt的createJwt方法中

        //写入cookie
        writeJwtCookie(response, jwt);
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取jwt
        String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
        if(jwt==null){
            //一旦jwt为空，则用户未登录，那么什么都不用做
            return;
        }
        try {
            //解析jwt
            Payload payload = jwtUtils.parseJwtAndRedis(jwt);
            String id = payload.getUserDetail().getId();
            jwtUtils.deleteJwt(id);
        } catch (Exception e) {
            //一旦解析出现异常，也什么都不用做，但最后cookie还是要删的
        }
        //删除redis和删除jwt可以都写在jwtUntils中
        //删除cookie
//        Cookie cookie = new Cookie(COOKIE_NAME, jwt);
//        cookie.setMaxAge(0);
//        response.addCookie(cookie);

        CookieUtils.deleteCookie(COOKIE_NAME,DOMAIN,response);



    }

    private void writeJwtCookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(COOKIE_NAME, jwt);
        //设置cookie最大存活时间
        cookie.setMaxAge(-1);
        //设置cookie的生效路径
        cookie.setPath("/");
        //设置cookie的作用域
        cookie.setDomain(DOMAIN);
        //设置cookie不让前端js操作
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }
}
